<template>
  <div>
      <el-button type="primary" icon="el-icon-plus" @click="add">添加分类</el-button>

      <el-table :data="list" style="margin:20px 0px;">
        <el-table-column type="expand">
          <template slot-scope="scope">
            <el-empty v-if="scope.row.subcategories.length <= 0" :image-size="30" description="暂无二级分类"></el-empty>
            <template v-else>
              <div class="subcate-item" v-for="(item,index) in scope.row.subcategories" :key="index">
                <img :src="`${$api.baseURL}${item.scpic}`" width="50px">
                <span>{{item.subcid}}</span>
                <span>{{item.subcname}}</span>
                <el-button type="danger" size="mini" @click="delSubcate(scope.row,index)">删除</el-button>
              </div>
            </template>
          </template>
        </el-table-column>
        <el-table-column label="ID" prop="cid" ></el-table-column>
        <el-table-column label="分类名称" prop="cname"></el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button type="primary" size="small">修改</el-button>
            <el-button type="danger" size="small" @click="del(scope)">删除</el-button>
            <el-button type="success" size="small" @click="addSubcate(scope)">添加</el-button>
          </template>
        </el-table-column>
      </el-table>

    <!-- 分页按钮 -->
    <el-pagination
      background
      layout="prev, pager, next"
      :total="count"
      :page-size="pageSize"
      :current-page="page"
      @current-change="changePage"
      >
    </el-pagination>

    <!-- 添加二级分类的弹出框 -->
    <el-dialog title="添加二级分类" :visible.sync="visible" :close-on-click-modal="false">
      <el-form label-width="80px">
        <el-form-item label="一级ID">
          <el-input v-model="form.cid" disabled autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="一级名称">
          <el-input v-model="form.cname" disabled autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="二级名称">
          <el-input v-model="subcate.subcname" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="分类图片">
          <el-upload :action="`${$api.baseURL}/admin/upload/classify`"
                    name="img"
                    :show-file-list="false"
                    :before-upload="beforeUpload"
                    :on-success="onSuccess"
                    :on-error="onError"
                    >
            <el-button v-if="subcate.scpic === ''">上传</el-button>
            <img v-else :src="`${$api.baseURL}${subcate.scpic}`" width="100px">
          </el-upload>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="visible = false">取 消</el-button>
        <el-button type="primary" @click="submit">提交</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
export default {
  data(){
    return {
      list: [],
      page: 1,
      pageSize: 2,
      count: 0,
      visible: false,
      form: {
        cid: 0,
        cname: '',
        subcategories: []
      },
      subcate: { //二级分类的对象
        subcid: 0,
        subcname: '',
        scpic: ''
      }
    }
  },
  created(){
    this.getData()
  },
  methods: {
    getData(){ //获取数据
      this.$http({
        path: this.$api.Classify.find, 
        params: {
          page: this.page,
          pageSize: this.pageSize
        }
      }).then(res=>{
        console.log(res);
        this.list = res.data
        this.page = res.page
        this.pageSize = res.pageSize,
        this.count = res.count
      })
    },
    add(){ //添加一级分类
      this.$prompt('请输入分类名称', '提示', {
          confirmButtonText: '添加',
          cancelButtonText: '取消',
          closeOnClickModal: false
        }).then(({ value }) => {
          this.$http({
            path: this.$api.Classify.add,
            method: 'post',
            params: {
              cid: this.count + 1,
              cname: value
            }
          }).then(res=>{
            this.$message({
              type: res.code === 200 ?'success':'error',
              message: res.msg
            });
            if(res.code === 200){
              this.getData()
            }
          })
        }).catch(() => {});
    },
    del(scope){ //删除一级分类
      this.$confirm(`确定要删除【${scope.row.cname}】吗？`, '提示', {
          confirmButtonText: '删除',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.$http({
            path: this.$api.Classify.del,
            params: {
              _id: scope.row._id
            }
          }).then(res=>{
            this.$message({
              type: res.code === 200 ? 'success':'error',
              message: res.msg
            });
            if(res.code === 200){
              this.getData()
            }
          })
          
        }).catch(() => {});
    },
    addSubcate(scope){ //点击添加二级分类按钮
       this.form = scope.row
       this.subcate = {
         subcid: 0,
         subcname: '',
         scpic: ''
       }
       this.visible = true
    },
    submit(){ //添加二级分类
        let subcid = this.form.subcategories.length + 1
        this.subcate.subcid = this.form.cid +''+ subcid

        this.form.subcategories.push(this.subcate)

        this.$http({
          path: this.$api.Classify.update,
          method: 'post',
          params: {
            data: JSON.stringify(this.form)
          }
        }).then(res=>{
          // console.log(res);
           this.$message({
              type: res.code === 200 ? 'success':'error',
              message: res.msg
            });
            if(res.code === 200){
              this.getData()
              this.visible = false
            }
        })
    },
    beforeUpload(file){ //上传前钩子
        console.log(file);
        let type = file.type === 'image/jpeg' || file.type === 'image/png'
        let size = file.size < 1024 * 1024

        if(!type){
          this.$message.warning('只能上传图片！')
        }else if(!size){
          this.$message.warning('图片不能大于1MB！')
        }

        return type && size
    },
    onSuccess(res){ //上传成功
        // console.log(res);
        if(res.code === 200){
          this.subcate.scpic = res.path
        }else{
          this.$message.error('上传失败')
        }
    },
    onError(){ //上传失败

    },
    delSubcate(row,index){ //删除二级分类
      row.subcategories.splice(index,1)
      this.$http({
          path: this.$api.Classify.update,
          method: 'post',
          params: {
            data: JSON.stringify(row)
          }
        }).then(res=>{
          // console.log(res);
          //  this.$message({
          //     type: res.code === 200 ? 'success':'error',
          //     message: res.msg
          //   });
          //   if(res.code === 200){
          //     let item = this.list[index]
          //     this.list.splice(index,1,item)
          //     // this.visible = false
          //   }
        })
    },
    changePage(page){ //切换页码
      // console.log(page);
      this.page = page
      this.getData()
    }
  }
}
</script>

<style scoped>
.subcate-item{
  height: 50px;
  margin: 10px 0px;
  box-sizing: border-box;
  padding: 0px 30px;
  display: flex;
  align-items: center;
  justify-content: space-around;
}
</style>